<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="baidu-site-verification" content="code-Vc9hmj7JE9" />
<meta name="google-site-verification" content="tMVEtTlHbEdIEga44DZi47Yu8Pl2shFKVZcqz6rfSW0" />
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://kun-bin.github.io/");
                } else {
                    history.back();
                }
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="/css/matery.css">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python," />










<meta name="description" content="知识点记录这次上课有一些是以前不太了解的知识点。">
<meta property="og:type" content="article">
<meta property="og:title" content="python课程记录-3">
<meta property="og:url" content="https://likun1208.github.io/2020/03/11/python%E8%AF%BE%E7%A8%8B%E8%AE%B0%E5%BD%95-3/index.html">
<meta property="og:site_name" content="左边">
<meta property="og:description" content="知识点记录这次上课有一些是以前不太了解的知识点。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-11T01:38:20.000Z">
<meta property="article:modified_time" content="2020-12-21T06:31:24.694Z">
<meta property="article:author" content="Kun Li">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://likun1208.github.io/2020/03/11/python课程记录-3/"/>





  <title>python课程记录-3 | 左边</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">左边</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>
	<script type="text/javascript" src="/js/echarts.min.js"></script>
    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://likun1208.github.io/2020/03/11/python%E8%AF%BE%E7%A8%8B%E8%AE%B0%E5%BD%95-3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kun Li">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="左边">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python课程记录-3</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-03-11T09:38:20+08:00">
                2020-03-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index">
                    <span itemprop="name">课程笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="知识点记录"><a href="#知识点记录" class="headerlink" title="知识点记录"></a>知识点记录</h3><p>这次上课有一些是以前不太了解的知识点。</p>
<a id="more"></a>
<h5 id="序列"><a href="#序列" class="headerlink" title="序列"></a>序列</h5><p>包括字符串、列表、元组、字节序列。</p>
<ol>
<li><p>索引访问：</p>
<p>有<code>n</code>个元素的数组，索引范围是<code>[0, n-1]</code>或<code>[-n, -1]</code>，也就是说，除了常规的类似其他语言中数组的下标索引方式，我们还可以通过<code>-1</code>来逆序访问。这在某些时候是很方便的一个操作，比如判断回文字符串。</p>
</li>
<li><p>遍历访问：</p>
<p>遍历也是用<code>for</code>循环，不过和其他语言不同的是，这里<code>for</code>循环中的<code>i</code>类型很随意，可以是<code>1, 2, 3, ...</code>也可以是元组、字符等，例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> c <span class="keyword">in</span> <span class="string">'hello'</span>:</span><br><span class="line">	print(c)</span><br></pre></td></tr></table></figure>
<p>这里的<code>c</code>是字符，最终会把<code>h</code>, <code>e</code>, <code>l</code>, <code>l</code>, <code>o</code> 逐行输出。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> t <span class="keyword">in</span> [(<span class="number">1</span>,<span class="number">2</span>),(<span class="number">3</span>,<span class="number">4</span>),(<span class="number">5</span>,<span class="number">6</span>)]</span><br><span class="line">	print(t,t[<span class="number">0</span>],t[<span class="number">1</span>])</span><br></pre></td></tr></table></figure>
<p>这里的<code>t</code>是元组，最终输出是：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(<span class="number">1</span>,<span class="number">2</span>) <span class="number">1</span> <span class="number">2</span></span><br><span class="line">(<span class="number">3</span>,<span class="number">4</span>) <span class="number">3</span> <span class="number">4</span></span><br><span class="line">(<span class="number">5</span>,<span class="number">6</span>) <span class="number">5</span> <span class="number">6</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>切片</p>
<p>序列<code>s</code>可以通过<code>s[i:j:k]</code>来截取其中的一部分，<code>i</code>是起点，<code>j</code>是终点，<code>k</code>是步长，注意这里的起点终点都可以是负数，结合上文可知，<code>s[::-1]</code>实际上就是序列的逆序。注意这个切片并不会改变序列<code>s</code>。想要将切片的下标信息保存下来，我们可以使用<code>slice(i:j:k)</code>函数。这里如果越界了也不会报错。</p>
</li>
<li><p>连接和重复</p>
<p>连接<code>+</code>：<code>s1+s2</code></p>
<p>重复<code>*</code>：<code>s*n</code> 或者 <code>n*s</code></p>
<p>增量赋值：<code>+=</code>和<code>*=</code></p>
<p>元组不可以<code>+=</code>序列，但是反过来序列<code>+=</code>元组是没问题的。</p>
</li>
<li><p>成员关系操作</p>
<p><code>in</code>和<code>not in</code>可以判断一个元素是否在序列中。</p>
<p><code>s.count(value)</code>可以统计<code>value</code>在序列<code>s</code>中出现的次数。</p>
<p><code>s.index(value, [start, [stop]])</code>查找value在序列指定范围 <code>[start,stop)</code>中第一次出现的下标。</p>
</li>
<li><p>序列内置函数</p>
<p><code>len</code> 单纯求序列长度</p>
<p><code>sorted</code>对序列排序并返回排序后的列表，不改变原始序列</p>
<p><code>reversed</code>逆序，不改动原序列，返回反向迭代器</p>
<p><code>max</code>和<code>min</code>求最大值和最小值，要求元素类型都一样</p>
<p><code>sum</code>序列求和，要求不能有非数字</p>
<p><code>enumerate</code>返回元素为<code>元组(计数，元素)</code> 的迭代器</p>
<p><code>zip</code>拼接多个对象<code>iter1、iter2…</code>的元素， 返回一个迭代器，其元素为各对象元素组成的元组。</p>
<p><code>all</code>和<code>any</code>判断序列的元素是否全部和部分为True</p>
</li>
<li><p>序列类型转换</p>
<p><code>str</code> <code>list</code> <code>tuple</code> <code>bytes</code> <code>bytearray</code>可以从字面意义看出是转成什么类型。</p>
</li>
<li><p>的</p>
</li>
<li><p>序列拆分</p>
<p><code>变量1,变量2,…,变量n = 序列</code>这样的赋值语句，可以把序列中的元素拆开赋值给前面的变量，不过类型要统一，比如序列中有元组，那前面对应位置的变量也要写成元组的形式。</p>
<p><code>*变量</code>的形式，可以把多个元素打包赋值给一个变量，但是只能出现一次。</p>
<p>可以用临时变量<code>_</code>来占位从而将指定位置的元素赋值给某个变量，例如<code>_, b, _ = (1, 2, 3)</code>就是把<code>2</code>赋值给<code>b</code>。</p>
</li>
</ol>
<h5 id="列表"><a href="#列表" class="headerlink" title="列表"></a>列表</h5><ol>
<li><p><code>del</code>删除元素，赋值修改元素</p>
</li>
<li><p><code>s.append(x)</code> 把<code>x</code>追加到<code>s</code>末尾</p>
</li>
<li><p><code>s.clear()</code> 删除所有元素</p>
</li>
<li><p><code>s.copy()</code> 复制</p>
</li>
<li><p><code>s.extend(t)</code> 和上面的<code>s.append(x)</code>是一样的，区别在于，<code>append</code>把<code>x</code>作为一个整体加到末尾，而<code>extend</code>把<code>x</code>作为一个新的列表合并到<code>s</code>的末尾。</p>
</li>
<li><p><code>s.insert(i,x)</code>插入</p>
</li>
<li><p><code>s.pop([i])</code>返回并移除下标为<code>i</code>的元素，<code>i</code>省略时默认为最后一个元素</p>
</li>
<li><p><code>s.remove(x)</code>移除列表中第一次出现的<code>x</code></p>
</li>
<li><p><code>s.reverse()</code>列表反转</p>
</li>
<li><p><code>s.sort()</code>列表排序</p>
</li>
<li><p>列表解析表达式：处理可迭代对象并生成结果列表，具体格式为<code>[express for i_1 in 可迭代对象1…for i_N in 可迭代对象N [if condition] ]</code></p>
<p>例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">[i <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>)]</span><br><span class="line">[i**<span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>) <span class="keyword">if</span> i%<span class="number">2</span>==<span class="number">0</span>]</span><br><span class="line">[(x+y,x*y) <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">2</span>) <span class="keyword">for</span> y <span class="keyword">in</span> range(<span class="number">2</span>,<span class="number">4</span>)]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 列表解析生成字典和集合</span></span><br><span class="line">a = [(<span class="string">'小黑'</span>,<span class="string">'领导'</span>,<span class="number">30000</span>),(<span class="string">'小白'</span>,<span class="string">'职员'</span>,<span class="number">10000</span>),(<span class="string">'小蓝'</span>,<span class="string">'职员'</span>,<span class="number">5000</span>)]</span><br><span class="line">&#123;i[<span class="number">0</span>]:i[<span class="number">2</span>] <span class="keyword">for</span> i <span class="keyword">in</span> a&#125;</span><br><span class="line"><span class="comment"># output: &#123;'小黑': 30000, '小白': 10000, '小蓝': 5000&#125;</span></span><br><span class="line">&#123;i[<span class="number">0</span>] <span class="keyword">for</span> i <span class="keyword">in</span> a <span class="keyword">if</span> i[<span class="number">2</span>]&gt;=<span class="number">10000</span>&#125;</span><br><span class="line"><span class="comment"># output: &#123;'小白', '小黑'&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="课堂练习"><a href="#课堂练习" class="headerlink" title="课堂练习"></a>课堂练习</h3><ol>
<li><p>已知一选手的各评委得分<code>score = [95, 85, 89, 88, 86, 95, 89, 98, 85, 75, 80]</code>，运用序列的各项操作求该选手的得分，计算规则：去掉一个最高分和一个最低分，剩下的分数计算平均分。</p>
<p>最直接的思路就是整体求和然后减去最大的和最小的再算平均值，也就是：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">score = [<span class="number">95</span>, <span class="number">85</span>, <span class="number">89</span>, <span class="number">88</span>, <span class="number">86</span>, <span class="number">95</span>, <span class="number">89</span>, <span class="number">98</span>, <span class="number">85</span>, <span class="number">75</span>, <span class="number">80</span>]</span><br><span class="line">s = (sum(score) - max(score) - min(score)) / (len(score) - <span class="number">2</span>)</span><br><span class="line">print(s)</span><br></pre></td></tr></table></figure>
</li>
<li><p>判断一个字符串是否是回文串：<code>a = &#39;abcdcba&#39;  b = &#39;abcdefg&#39;</code></p>
<p>这个题有很多思路，最快的办法就是用前面提到的<code>s[::-1]</code>来实现逆序，即：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">is_palindromic4</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> num == num[::<span class="number">-1</span>]</span><br><span class="line">a = <span class="string">'abcdcba'</span></span><br><span class="line">b = <span class="string">'abcdefg'</span></span><br><span class="line">print(is_palindromic4(b))</span><br></pre></td></tr></table></figure>
<p>也可以选择把字符串转成<code>list</code>或者<code>tuple</code>然后使用<code>reverse</code>函数来实现逆序。即：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">list(a)==list(reverse(a))</span><br><span class="line">tuple(a)==tuple(reverse(a))</span><br></pre></td></tr></table></figure>
</li>
<li><p>下面代码执行后的<code>s</code>是（）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">s = [<span class="string">'a'</span>, <span class="string">'b'</span>]</span><br><span class="line">s.append([<span class="number">1</span>, <span class="number">2</span>])</span><br><span class="line">s.extend(<span class="string">'34'</span>)</span><br><span class="line">s.extend([<span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line">s.insert(<span class="number">1</span>, <span class="number">7</span>)</span><br><span class="line">s.insert(<span class="number">10</span>, <span class="number">8</span>)</span><br><span class="line">s.pop(<span class="number">2</span>)</span><br><span class="line">s.remove(<span class="string">'a'</span>)</span><br><span class="line">s[<span class="number">4</span>:] = []</span><br><span class="line">s.reverse()</span><br></pre></td></tr></table></figure>
<p>对照每个函数的作用可以很容易判断出最后的结果是<code>[&#39;4&#39;,&#39;3&#39;,[1,2],7]</code></p>
</li>
</ol>
<h3 id="作业"><a href="#作业" class="headerlink" title="作业"></a>作业</h3><ol>
<li><p>使用<code>+</code>,<code>-</code>,<code>*</code>,<code>/</code>,<code>**</code>运算符和数字<code>2</code>,<code>3</code>,<code>4</code>,<code>5</code>，构造一个表达式，该表达式中上述4个数字和3种不同运算符各用一次，使得表达式的结果为24，打印出满足条件的表达式。</p>
<p>提示：</p>
<p>(1)构建表达式字符串，然后用内置函数<code>eval</code>计算该字符串 ，例如<code>eval(&#39;3*4/2+5&#39;)</code>返回<code>11.0</code>； </p>
<p>(2)两字符串可通过”+”连接成一个字符串，如<code>’he’+’llo’</code>会 得到<code>’hello’</code>； </p>
<p>(3)本题关键在于求排列，排列有多种实现方式，例如循环。</p>
<p>根据提示很容易想到一个思路：把数字的全排列和运算符的取3个排列分别列出来，然后逐一组合成字符串，使用<code>eval</code>计算结果，如果是24，就输出。查找资料后发现<code>python</code>有一个算排列的库函数<code>itertools.permutations(s, n)</code>，该函数返回列表<code>s</code>中取<code>n</code>个元素的排列结果，该结果也是一个列表，也就是说我们可以通过该函数得到数字和运算符的排列结果，并<code>for</code>循环遍历，将它们组成计算表达式并求结果，然后输出。代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> itertools</span><br><span class="line">op = [<span class="string">'+'</span>, <span class="string">'-'</span>, <span class="string">'*'</span>, <span class="string">'/'</span>, <span class="string">'**'</span>]</span><br><span class="line">num = [<span class="string">'2'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>, <span class="string">'5'</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> itertools.permutations(num, <span class="number">4</span>):</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> itertools.permutations(op, <span class="number">3</span>):</span><br><span class="line">        s = i[<span class="number">0</span>] + j[<span class="number">0</span>] + i[<span class="number">1</span>] + j[<span class="number">1</span>] + i[<span class="number">2</span>] + j[<span class="number">2</span>] + i[<span class="number">3</span>]</span><br><span class="line">        <span class="keyword">if</span> float(eval(s)) == <span class="number">24.0</span>:</span><br><span class="line">            print(s)</span><br></pre></td></tr></table></figure>
<p>此外，<code>python</code>中完成24点游戏的思路还有很多很多，复杂一些的办法可以是构造二叉树，然后遍历节点。</p>
</li>
<li><p>输入一个列表，然后删除该列表中的重复的元素，要求删除重复元素后还保持原排序，最后输出结果。例如，输入列表 <code>[0, 1, 1, 1, 3, 0, 3, 2]</code>，输出 <code>[0, 1, 3, 2]</code>。</p>
<p>这个题也有很多思路，比如逐个比较等。有一种很便捷的方法是，对输入列表生成字典，这样就按顺序去掉了重复元素，再将字典的<code>key</code>转成列表即可，代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">list1 = eval(input(<span class="string">'请输入一个列表：'</span>))</span><br><span class="line">list2 = dict.fromkeys(list1)</span><br><span class="line">list3 = list(list2.keys())</span><br><span class="line">print(list3)</span><br></pre></td></tr></table></figure></li>
</ol>

      
    </div>
    
    
    

    

    

    
	
	<div>
		
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
		
	</div>
	
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/03/09/Let-s-Build-A-Simple-Interpreter%E7%AC%94%E8%AE%B0-5/" rel="next" title="Let-s-Build-A-Simple-Interpreter笔记-5">
                <i class="fa fa-chevron-left"></i> Let-s-Build-A-Simple-Interpreter笔记-5
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/03/12/Let-s-Build-A-Simple-Interpreter%E7%AC%94%E8%AE%B0-6/" rel="prev" title="Let-s-Build-A-Simple-Interpreter笔记-6">
                Let-s-Build-A-Simple-Interpreter笔记-6 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="Kun Li" />
            
              <p class="site-author-name" itemprop="name">Kun Li</p>
              <p class="site-description motion-element" itemprop="description">三月樱，六月雪，也望尘莫及</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
				<a href="/archives/">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">27</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/likun1208" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="likun@mail.bnu.edu.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#知识点记录"><span class="nav-number">1.</span> <span class="nav-text">知识点记录</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#序列"><span class="nav-number">1.0.1.</span> <span class="nav-text">序列</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#列表"><span class="nav-number">1.0.2.</span> <span class="nav-text">列表</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#课堂练习"><span class="nav-number">2.</span> <span class="nav-text">课堂练习</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#作业"><span class="nav-number">3.</span> <span class="nav-text">作业</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kun Li</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('Success')
          else $(this).text('Fail')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('Copy')
        }, 300)
      }).append(e)
    })
  </script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/z16.model.json"},"display":{"position":"left","width":175,"height":350},"mobile":{"show":false},"log":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
